import { type ColumnDef } from '@tanstack/react-table'
import { cn } from '@/lib/utils'
import { Checkbox } from '@/components/ui/checkbox'
import LongText from '@/components/long-text'
import { type Upload } from '../data/schema'
import { DataTableColumnHeader } from './data-table-column-header'
import { DataTableRowActions } from './data-table-row-actions'
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
import { ImagePreview } from "@/components/image-preview"
import { getRouteApi } from '@tanstack/react-router'

export const columns: ColumnDef<Upload>[] = [
  {
    id: 'select',
    header: ({ table }) => (
      <Checkbox
        checked={
          table.getIsAllPageRowsSelected() ||
          (table.getIsSomePageRowsSelected() && 'indeterminate')
        }
        onCheckedChange={(value) => table.toggleAllPageRowsSelected(!!value)}
        aria-label='Select all'
        className='translate-y-[2px]'
      />
    ),
    meta: {
      className: cn(
        'sticky md:table-cell left-0 z-10 rounded-tl',
        'bg-background group-hover/row:bg-muted group-data-[state=selected]/row:bg-muted'
      ),
    },
    cell: ({ row }) => (
      <Checkbox
        checked={row.getIsSelected()}
        onCheckedChange={(value) => row.toggleSelected(!!value)}
        aria-label='Select row'
        className='translate-y-[2px]'
      />
    ),
    enableSorting: false,
    enableHiding: false,
  },
  {
    accessorKey: 'id',
    header: ({ column }) => (
      <DataTableColumnHeader column={column} title='ID' />
    ),
    cell: ({ row }) => (
      <LongText className='max-w-36'>{String(row.getValue('id') || '')}</LongText>
    ),
    enableHiding: false,
  },
  {
    accessorKey: 'url',
    header: ({ column }) => (
      <DataTableColumnHeader column={column} title='Preview' />
    ),
    cell: ({ row }) => {
      const url = String(row.getValue('url') || '');
      const isImage = /\.(jpeg|jpg|png|gif|webp|svg)$/i.test(url);

      if (isImage) {
        return (
          <ImagePreview src={url} alt={`Preview of ${row.getValue('name') || 'image'}`}>
            <Avatar>
              <AvatarImage src={url} />
              <AvatarFallback>img</AvatarFallback>
            </Avatar>
          </ImagePreview>
        );
      }

      return (
        <Avatar>
          <AvatarImage src={url} />
          <AvatarFallback>file</AvatarFallback>
        </Avatar>
      );
    },
    enableSorting: false,
  },
  {
    accessorKey: 'name',
    header: ({ column }) => (
      <DataTableColumnHeader column={column} title='Name' />
    ),
    cell: ({ row }) => (
      <LongText className='max-w-36'>{String(row.getValue('name') || '')}</LongText>
    ),
    enableSorting: false,
  },
  {
    accessorKey: 'category',
    header: ({ column }) => (
      <DataTableColumnHeader column={column} title='Category' />
    ),
    cell: ({ row }) => {
      const routeApi = getRouteApi('/_authenticated/uploads/')
      const { uploadDict } = routeApi.useLoaderData()
      const categoryValue = row.getValue('category')
      const categoryLabel = uploadDict.find(item => item.value === categoryValue?.toString())?.name
      return <div className='w-fit text-nowrap'>{categoryLabel}</div>
    },
    enableSorting: false,
  },
  {
    accessorKey: 'file_size',
    header: ({ column }) => (
      <DataTableColumnHeader column={column} title='File Size' />
    ),
    cell: ({ row }) => (
      <div className='w-fit text-nowrap'>{`${((row.getValue('file_size') as number) / 1024).toFixed(2)} KB`}</div>
    ),
    enableSorting: false,
  },

  {
    accessorKey: 'image_width',
    header: ({ column }) => (
      <DataTableColumnHeader column={column} title='Width' />
    ),
    cell: ({ row }) => (
      <div className='w-fit text-nowrap'>{String(row.getValue('image_width') || '')}</div>
    ),
    enableSorting: false,
  },
  {
    accessorKey: 'image_height',
    header: ({ column }) => (
      <DataTableColumnHeader column={column} title='Height' />
    ),
    cell: ({ row }) => (
      <div className='w-fit text-nowrap'>{String(row.getValue('image_height') || '')}</div>
    ),
    enableSorting: false,
  },
  {
    accessorKey: 'ext',
    header: ({ column }) => (
      <DataTableColumnHeader column={column} title='Extension' />
    ),
    cell: ({ row }) => (
      <div className='w-fit text-nowrap'>{String(row.getValue('ext') || '')}</div>
    ),
    enableSorting: false,
  },

  {
    accessorKey: 'created_at',
    header: ({ column }) => (
      <DataTableColumnHeader column={column} title='Created At' />
    ),
    cell: ({ row }) => <div>{String(row.getValue('created_at') || '')}</div>,
    enableSorting: false,
  },
  {
    id: 'actions',
    cell: DataTableRowActions,
  },
]
